package com.cs342.g4.memaps;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import basicClasses.Friend;
import basicClasses.FriendRequestObject;
import basicClasses.LoginObject;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import asyncTasks.DeleteFriend;
import asyncTasks.GetFriends;
import asyncTasks.VerifyUserExists;

public class ViewFriends extends Activity {

	public static ListView listFriends;
	private HashSet<String> friends = new HashSet<String>();
	private ArrayAdapter<String> listFriendsAdapter;
	private EditText friendSearch;
	private String curUser;
	private String curPass;
	SharedPreferences mPrefs;

	@SuppressWarnings("unchecked")
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActionBar ab = getActionBar(); ab.setDisplayShowTitleEnabled(false); 
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		setContentView(R.layout.activity_view_friends);

		Context mContext = this.getApplicationContext();
		mPrefs = mContext.getSharedPreferences("myPrefs", MODE_PRIVATE);

		curUser = mPrefs.getString("username", "");
		curPass = mPrefs.getString("password", "");
		LoginObject lo = new LoginObject(curUser,curPass);


		ArrayList<Friend> friendsFromDB = new ArrayList<Friend>(); 
		GetFriends getFriendsTask = new GetFriends();
		try {
			friendsFromDB = getFriendsTask.execute(lo).get();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}
		populateFriendsTask popTask = new populateFriendsTask();
		friends.clear();

		Button addNew = (Button) findViewById(R.id.newFriend);
		Button reqsts = (Button) findViewById(R.id.friendReqsts);
		friendSearch = (EditText) findViewById(R.id.friendSearch);

		addNew.setOnClickListener(new OnClickListener() {

			boolean exists = false;
			@Override
			public void onClick(View v) {
				VerifyUserExists newFriend = new VerifyUserExists();
				FriendRequestObject frReqst = new FriendRequestObject(curUser,friendSearch.getText().toString());
				try {
					exists = newFriend.execute(frReqst).get();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}	

				if(!exists){
					friendSearch.setError("Not a Valid User");
					friendSearch.requestFocus();
				}
				else{
					Toast toast = Toast.makeText(getApplicationContext(),
					  "Friend Request Sent", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 20, 20);
					toast.show();
				}
				friendSearch.setText("");
			}
		});

		reqsts.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent vFriendsR = new Intent(ViewFriends.this, ViewFriendReqsts.class);
				startActivity(vFriendsR);
			}
		});

		friendSearch.addTextChangedListener(new TextWatcher(){

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {    
				listFriendsAdapter.getFilter().filter(s);
			}

			@Override
			public void afterTextChanged(Editable s) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {                            
			}

		});
	}

	@Override	
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();	
		inflater.inflate(R.layout.menu_items, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item){
		switch (item.getItemId()){
		case R.id.menu_favorites:
			Intent favs = new Intent(ViewFriends.this, FavoritePlacesActivity.class);
			startActivity(favs);
			return true;
		case R.id.menu_backToMap:
			Intent backToMap = new Intent(ViewFriends.this, MainActivity.class);
			startActivity(backToMap);
			finish();
			return true;
		case R.id.menu_logout:
			SharedPreferences.Editor edit = mPrefs.edit();
			edit.putString("username", "");
			edit.putString("password", "");
			edit.commit();

			Intent loginAct = new Intent(ViewFriends.this, LoginActivity.class);
			startActivity(loginAct);
			finish();
			return true;
		}
		return false;
	}

	public boolean onPrepareOptionsMenu(Menu menu){
		MenuItem mapType = menu.findItem(R.id.menu_setMapType);
		MenuItem viewFr = menu.findItem(R.id.menu_viewFriends);
		viewFr.setVisible(false);
		mapType.setVisible(false);
		return true;		
	}

	private class populateFriendsTask extends AsyncTask<ArrayList<Friend>, Void, HashSet<String>> {

		@Override
		protected HashSet<String> doInBackground(ArrayList<Friend>... params) {

			for(Friend friend: params[0]){
				friends.add(friend.friendName);
			}

			return friends;
		}

		@Override
		public void onPostExecute(HashSet<String> friends){
			SharedPreferences.Editor edit = mPrefs.edit();
			edit.putStringSet("friends", friends);
			edit.commit();

			ArrayList<String> displayFriends = new ArrayList<String>();
			for(String friend: friends){
				displayFriends.add(friend);
			}

			listFriends = (ListView) findViewById(R.id.friendsList);    
			listFriendsAdapter = new ArrayAdapter<String>(ViewFriends.this,
					android.R.layout.simple_list_item_1, displayFriends);
			listFriends.setAdapter(listFriendsAdapter);
			
			listFriends.setLongClickable(true);
			listFriends.setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override
				public boolean onItemLongClick(AdapterView<?> parent, View view,
						int position, long id) {
					//popup to delete a friend
					deleteFriendPrompt(view);		
					return true;
				}
			});		
		}
	}
	
	public void deleteFriendPrompt(final View v){
		LayoutInflater inflater = (LayoutInflater) ViewFriends.this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.popup_deletefriend, null, false);
		final PopupWindow popup = new PopupWindow(view,300,130,true);
		Button yes = (Button) view.findViewById(R.id.yesDel);
		Button no = (Button) view.findViewById(R.id.noDel);
		TextView deleteMe = (TextView) view.findViewById(R.id.deleteMe);
		deleteMe.setText(((TextView)v).getText().toString());
		popup.showAtLocation(v, Gravity.CENTER, 10, 10);
		popup.setFocusable(true);
		
		
		yes.setOnClickListener(new OnClickListener() {
			
			@SuppressWarnings("unchecked")
			@Override
			public void onClick(View view) {
				popup.dismiss();
				LoginObject lo = new LoginObject(curUser,((TextView)v).getText().toString());
				DeleteFriend deleteFriend = new DeleteFriend();
				try {
					deleteFriend.execute(lo).get();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				} catch (ExecutionException e1) {
					e1.printStackTrace();
				}	
				
				LoginObject lo2 = new LoginObject(curUser,curPass);
				ArrayList<Friend> friendsFromDB = new ArrayList<Friend>(); 
				GetFriends getFriendsTask = new GetFriends();
				try {
					friendsFromDB = getFriendsTask.execute(lo2).get();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				} catch (ExecutionException e1) {
					e1.printStackTrace();
				}
				populateFriendsTask popTask = new populateFriendsTask();
				popTask.execute(friendsFromDB);
				friends.clear();
			}
		});
		
		no.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				popup.dismiss();
			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onResume() {
		super.onResume();

		curUser = mPrefs.getString("username", "");
		curPass = mPrefs.getString("password", "");
		LoginObject lo = new LoginObject(curUser,curPass);
		ArrayList<Friend> friendsFromDB = new ArrayList<Friend>(); 
		GetFriends getFriendsTask = new GetFriends();
		try {
			friendsFromDB = getFriendsTask.execute(lo).get();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}
		populateFriendsTask popTask = new populateFriendsTask();
		popTask.execute(friendsFromDB);
		friends.clear();
	}


}
